<template>
  <scroll-view scroll-x class="tab-bar" :scroll-left="scrollLeft" :scroll-with-animation="true">
    <view class="tab-bar-wrapper flex">
      <view
        v-for="(item, index) in list"
        :key="item.id"
        class="tab-bar-item flex flex-col items-center"
        :class="[current === index ? 'tab-bar-item-active' : '']"
        :style="{ color: current === index ? `#${activeColor}` : '#303030' }"
        @click="handleClick(item, index)"
      >
        <text class="tab-bar-text">
          {{ item.name }}
        </text>
        <image v-if="current === index" class="tab-bar-img" :src="iconUrl" />
      </view>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue';
import type { StageList } from '@/api/course/types';

const props = withDefaults(defineProps<{
  list: StageList[];
  activeColor?: string;
  modelValue?: number;
  iconUrl?: string;
}>(), {
  activeColor: '303030',
  modelValue: 0,
  iconUrl: 'https://aireader-1302868088.cos.ap-nanjing.myqcloud.com/mini_icon/icon_2.png',
});

const emit = defineEmits(['update:modelValue', 'change', 'updateScrollLeft']);

const instance = getCurrentInstance();

const current = ref(props.modelValue);
const scrollLeft = ref(0);

// 计算滚动位置
const calculateScrollLeft = () => {
  const query = uni.createSelectorQuery().in(instance?.proxy);
  const windowWidth = uni.getSystemInfoSync().windowWidth;

  query.selectAll('.tab-bar-item').boundingClientRect((rects: any) => {
    if (!rects?.length)
      return;

    let totalWidth = 0;
    // 计算目标item的左边距离
    for (let i = 0; i < current.value; i++) {
      totalWidth += rects[i].width;
    }

    const currentItemWidth = rects[current.value]?.width;

    // 计算最大可滚动距离
    const maxScrollLeft = rects.reduce((sum: number, rect: any) => sum + rect.width, 0) - windowWidth;

    // 确保当前item完全显示在可视区域内
    let newScrollLeft = totalWidth - (windowWidth - currentItemWidth) / 2;

    // 处理边界情况
    newScrollLeft = Math.max(0, Math.min(newScrollLeft, maxScrollLeft));

    scrollLeft.value = newScrollLeft;
    emit('updateScrollLeft', scrollLeft.value);
  }).exec();
};

// 监听外部v-model的变化
watch(() => props.modelValue, (newVal) => {
  current.value = newVal;
  nextTick(() => {
    calculateScrollLeft();
  });
}, { immediate: true });

// 点击标签
const handleClick = (item: StageList, index: number) => {
  if (current.value === index)
    return;
  current.value = index;
  emit('update:modelValue', index);
  emit('change', item);
  nextTick(() => {
    calculateScrollLeft();
  });
};
</script>

<style lang="scss" scoped>
.tab-bar {
  max-width: 750rpx;
  height: 70rpx;
  white-space: nowrap;

  .tab-bar-wrapper {
    height: 100%;
    display: inline-flex;
  }

  .tab-bar-item {
    height: 100%;
    padding: 0 20rpx;
    position: relative;

    &-active {
      font-weight: bold;
    }
  }

  .tab-bar-text {
    font-size: 36rpx;
    line-height: 54rpx;
  }

  .tab-bar-icon {
    position: absolute;
    bottom: 8rpx;
    left: 50%;
    transform: translateX(-50%);
  }

  .tab-bar-img {
    width: 56rpx;
    height: 16rpx;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>
